
//
//  EditSongCanAddressController.m
//  FD
//
//  Created by xiaofang wang on 2018/11/15.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  11-15 编辑送餐地址  MyAddNewAddressController.h

#import "EditSongCanAddressController.h"

#import "MySerachViewControllerXinDeman123.h"

//Veiw
#import "AddressUpViewXin.h"
#import "AddressDownViewXin.h"
#import "NewAddressLabelTextField.h"

//model
#import "MyAddressModel.h"
@interface EditSongCanAddressController ()
/**上*/
@property (nonatomic, strong) AddressUpViewXin *upView;
/**下*/
@property (nonatomic, strong) AddressDownViewXin *downView;
/**保存按钮*/
@property (nonatomic, strong) UIButton *saveBtn;

/**hud*/
@property (nonatomic, strong) MBProgressHUD *hud;
/**标记选中的性别 0先生 1女士  没有默认值*/
@property (nonatomic, strong) NSNumber *sexNumber;

/**记录坐标1-23
 第一次是:跳转Google地图选择地址,然后将经纬度回调过来 ❌不要了
 第二次是:输入地址,调Google地图的接口获取地址对应的坐标。❌不要了
 第三次是:跳转搜索控制器。点击地址后回调坐标 1-23
 */
@property (nonatomic, assign) CLLocationCoordinate2D tempCoordinate;
@end

@implementation EditSongCanAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

#pragma mark 一 setupUI
- (void)setupUI {
    self.view.backgroundColor = kMainLightGrayColor;
    self.navigationItem.title = NSLocalizedString(L_EditDeliveryAddress, @"编辑送餐地址");

    //取消导航条线:会导致莫名奇妙的问题。
    //    [self fd_hideNavigationBlackLine];
    
    //2019-1-8解决烦人的导航条偏移问题
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    //    self.navigationController.navigationBar.translucent = NO;
    
    //导航条文字
    self.navigationItem.title = NSLocalizedString(NewAddress, @"新增送餐地址");
    //上
    [self.view addSubview:self.upView];
    
    //小
    [self.view addSubview:self.downView];
    
    //"保存"按钮
    [self.view addSubview:self.saveBtn];
    
    [self setLayout];
    //    [self setDevelopDefaultValue]; //develop默认地址
    
    

    [self updateViewWithMyAddressModel:self.addressModel];
}


- (void)setLayout {
    [self.upView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        CGFloat top = 10;
        if (self.fromWhichVC == 1) { //从 “送餐地址和时间” vc过来的
            top += FD_NavH;
        }else if (self.fromWhichVC == 2) { //2 我的-->配送地址-->新增按钮
            top += FD_NavH;
        }
        
        make.top.equalTo(self.view.mas_top).offset(top);
        make.height.mas_equalTo(155);
    }];
    
    [self.downView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(155);
        make.top.equalTo(self.upView.mas_bottom).offset(10);
    }];
    
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(50);
    }];
}

- (void)setDevelopDefaultValue {
    self.upView.contactLT.textField.text = @"张三";
    self.upView.phoneLT.textField.text = @"10086";
    self.downView.addressLT.textField.text = @"3 Kenley ave"; //✅ 在配送范围内
    self.downView.houseNumberLT.textField.text = @"905";
    self.downView.postCodeLT.textField.text = @"310000";
    
    //    @"3 Kenley ave" ✅
    //    Doyle road
    //    hebry street
    //    cathedral road
}

#pragma mark - getter
- (AddressUpViewXin *)upView {
    if (!_upView) {
        _upView = [[AddressUpViewXin alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 155)];
        FDWeakSelf;
        _upView.addressUPViewXinClickSexViewBlock = ^(NSNumber * _Nonnull sexNum) {
            weakSelf.sexNumber = sexNum;
        };
    }
    return _upView;
}

//!!!!:2019-1-23新需求修改
- (AddressDownViewXin *)downView {
    if (!_downView) {
        _downView = [[AddressDownViewXin alloc] initWithFrame:CGRectMake(0, self.upView.rb_bottom+10, SCREEN_WIDTH, 155)];
        
        FDWeakSelf;
        //2019-1-23new demand
        _downView.clickAddressTFBlock = ^{
            //            [self->_downView.addressLT.textField endEditing:YES]; //封装起来,尽量不要暴露。
            FDLog(@"点击了输入框");
            [weakSelf skipToMySearchVC];
        };
    }
    return _downView;
}

- (void)skipToMySearchVC {
    MySerachViewControllerXinDeman123 *searchVC = [[MySerachViewControllerXinDeman123 alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    searchVC.clickMySearchVCBlock = ^(CLLocationCoordinate2D coordinate, NSString * _Nonnull formattedAddress) {
        FDLog(@":%f=:%f=:%@",coordinate.latitude,coordinate.longitude,formattedAddress);
        self.downView.addressLT.textField.text = formattedAddress;
        
        //保存坐标
        self.tempCoordinate = coordinate;
    };
}


- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_saveBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        
        [_saveBtn setTitle:NSLocalizedString(L_Save, @"保存") forState:(UIControlStateNormal)];
        _saveBtn.backgroundColor = kMainRedColor;
        [_saveBtn addTarget:self action:@selector(clickSaveAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _saveBtn;
}


//2019-2-13防止按钮重复点击
- (void)clickSaveAction:(UIButton *)btn {
    
    //第一个region，修改后， 你给我传空字符串"" 或者 null就行
    //下面的 zipCode houseNumber 分别表示邮政编码与门牌号码
    NSString *name = self.upView.contactLT.textField.text;
    NSString *phone = self.upView.phoneLT.textField.text;
    NSString *address = self.downView.addressLT.textField.text;
    NSString *houseNumber = self.downView.houseNumberLT.textField.text;
    NSString *postCode = self.downView.postCodeLT.textField.text;
    
    //防空判断
    if ([NSString isEmptyString:name]) {
        [JRToast showWithText:NSLocalizedString(Home_put_your_contacts_name, @"请输入联系人姓名")];
        return;
    }
    if ([NSString isEmptyString:phone]) {
        [JRToast showWithText:NSLocalizedString(ToastPleaseInputPhone, @"请输入电话")];
        return;
    }
    if ([NSString isEmptyString:address]) {
        [JRToast showWithText:NSLocalizedString(ToastPleaseInputDetailAddress, @"请输入详细地址")];
        return;
    }
    if ([NSString isEmptyString:houseNumber]) {
        [JRToast showWithText:NSLocalizedString(ToastPleaseInputHouseNumber, @"请输入门牌号")];
        return;
    }
    
    //2019-2-16 非必填
    //    if ([NSString isEmptyString:postCode]) {
    //        [JRToast showWithText:NSLocalizedString(ToastPleaseInputZipCode, @"请输入邮政编码")];
    //        return;
    //    }
    
    //性别没有默认值。
    if ([NSString isEmptyString:[NSString stringWithFormat:@"%@",self.sexNumber]]) {
        NSString *qxzxbStr = NSLocalizedString(PleaseSelectGender, @"请选择性别");
        [JRToast showWithText:qxzxbStr];
        return;
    }
    
    //设置请求参数
    NSMutableDictionary *pardicM = @{}.mutableCopy;
    [pardicM setValue:name forKey:@"consignee"]; //联系人
    //    [pardicM setValue:@(0) forKey:@"sex"]; //性别  OC:NSNumber  服务器:int
    [pardicM setValue:self.sexNumber forKey:@"sex"]; //性别  OC:NSNumber  服务器:int
    
    [pardicM setValue:phone forKey:@"phone"]; //电话
    [pardicM setValue:@"" forKey:@"region"]; //传空
    [pardicM setValue:address forKey:@"detail"]; //地址
    
    if (![NSString isEmptyString:postCode]) { //2019-2-16 非必填
        [pardicM setValue:postCode forKey:@"zipCode"]; //邮编 新增
    }
    
    [pardicM setValue:houseNumber forKey:@"houseNumber"]; //门牌号 新增

    //2019-2-20新加收货地址编号
    [pardicM setValue:self.addressModel.addressId forKey:@"id"];
    
    
    //2019-1-23
    NSNumber *lat = @(self.tempCoordinate.latitude);
    NSNumber *lng = @(self.tempCoordinate.longitude);
    if (lat && lng) { //非空
        [pardicM setValue:lat forKey:@"latitude"];
        [pardicM setValue:lng forKey:@"longitude"];

        [self request2EditAddressDic:pardicM savaButton:btn];
        
    }else {
        FDLog(@"经纬度为空:%@-%@",lat,lng);
    }
}

- (void)request2EditAddressDic:(NSDictionary *)dic savaButton:(UIButton *)btn {
    btn.enabled = NO;
    
    [FDHttpAPi requestUserAddressEditWithParDic:dic successBlock:^(id responseObjc) {
        
        btn.enabled = YES;
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"请求失败:%@",[error localizedDescription]);
    }];
}


/**
 0.验证输入内容合法性
 
 1.调google接口将 "文字地址" --> 经纬度 -->读取经纬度
 a.地址转坐标接口文档：https://developers.google.com/maps/documentation/geocoding/start?hl=zh-CN
 b.请求参数：https://maps.googleapis.com/maps/api/geocode/json?address=【替换为detail字段的详细地址】&components=country:IE&key=【替换为接口请求密钥】
 c.请求示例：https://maps.googleapis.com/maps/api/geocode/json?address=3%20Kenley%20ave&components=country:IE&key=AIzaSyCNRNJ_-QLQ-Bh1mVHqFV-82tZsYvfI4cs
 
 2.经纬度+其他参数 -->调接口传给服务器。 /user/shipping_address/save
 
 3.使用信号量进行处理吧
 */
#pragma mark - 网络请求

#pragma mark - 专供子类使用
/**2019-1-18 专供子类使用 根据传递进来的sex 设置默认选中的按钮*/
- (void)updateViewWithMyAddressModel:(MyAddressModel *)model {
    
    //0.联系人
    self.upView.contactLT.textField.text = model.consignee;
    //1.性别
    [self.upView changeSex:model.sex];
    
    //2.电话
    self.upView.phoneLT.textField.text = model.phone;
    
    
    //3.详细地址
    self.downView.addressLT.textField.text = model.detail;
    //4.门牌号
    self.downView.houseNumberLT.textField.text = model.houseNumber;
    self.downView.postCodeLT.textField.text = model.zipCode;
    
    
    //2019-2-16 fix bug
    self.sexNumber = model.sex; //2019-2-16同时更新性别号
    //记录坐标
    self.tempCoordinate = CLLocationCoordinate2DMake([model.latitude floatValue], [model.longitude floatValue]);
}
@end
